/**
 * Tmd_1.1.js
 * Date: 2019/9/1
 * MD-TheHot: dcc505c445a9959489b1bee76d3020c9ab05a367
 */
const _config = {
    yingtaoyun: {
        name: "樱桃云",
        method: "get",
        resType: "string",
        url: "http://www.cherry888.top:8000/doApi/",
        phone_key: "phone",
        token_key: "token",
        item_key: "sid",
        split_key: "|",
        getToken: {
            login_api: "loginIn",
            user_key: "name",
            pwd_key: "password",
            ext: {
                author: "thehot"
            },
        },
        getPhone: {
            getPhone_api: "getPhone",
            vno: {
                key: 'vno',
                val: ['0', '1']
            },
            type: {
                key: 'phoneType',
                val: ['1', '2', '3']
            },
            ext: {
                author: "thehot"
            },
        },
        getCode: {
            getCode_api: "getMessage",
            ext: {},
        },
        recPhone: {
            recPhone_api: "cancelRecv"
        },
        adbPhone: {
            adbPhone_api: "addBlacklist"
        },
        getSummary: {
            getSummary_api: "getSummary"
        }
    }
}

function Tmd(debug) {
    this.debug = debug
};

Tmd.prototype = {
    getToken: function () {
        var t_conf = this._conf.getToken;
        var login_api = t_conf.login_api;
        var url_obj = {};
        url_obj[t_conf.user_key] = this.user;
        url_obj[t_conf.pwd_key] = this.pwd;
        Object.assign(url_obj, t_conf.ext);
        var url = this._conf.method == "get" ? this._conf.url + login_api + "?" + this.encodeFormData(url_obj) : this._conf.url + login_api;
        try {
            var res = this._conf.method === "get" ? this.hddp(url) : this.hddp(url, url_obj);
            return this.regxToken(res, this._conf.split_key);
        } catch (e) {
            console.error("获取Token字串失败！");
            return -1;
        }
    },
    getSummary: function () {
        var s_conf = this._conf.getSummary;
        var getSummary_api = s_conf.getSummary_api;
        var url_obj = {};
        url_obj[this._conf.token_key] = this.token;
        var url = this._conf.method == "get" ? this._conf.url + getSummary_api + "?" + this.encodeFormData(url_obj) : this._conf.url + getSummary_api;
        try {
            var res = this._conf.method === "get" ? this.hddp(url) : this.hddp(url, url_obj);
            return res;
        } catch (e) {
            console.error("获取账户信息失败！");
            return -1;
        }
    },
    getPhone: function (phone) {
        var p_conf = this._conf.getPhone;
        var getPhone_api = p_conf.getPhone_api;
        var url_obj = {};
        if (/\d{11}/.test(phone) && typeof phone == 'string') {
            url_obj[this._conf.phone_key] = phone;
        };
        url_obj[this._conf.token_key] = this.token;
        url_obj[this._conf.item_key] = this.item;
        url_obj[p_conf.vno.key] = this.vno ? p_conf.vno.val[this.vno] : "";
        url_obj[p_conf.type.key] = this.phoneType ? p_conf.type.val[this.phoneType] : "";
        Object.assign(url_obj, p_conf.ext);
        var url = this._conf.method == "get" ? this._conf.url + getPhone_api + "?" + this.encodeFormData(url_obj) : this._conf.url + getPhone_api;
        try {
            var res = this._conf.method === "get" ? this.hddp(url) : this.hddp(url, url_obj);
            return this.regxPhone(res, this._conf.split_key);
        } catch (e) {
            console.error("获取手机号失败！");
            return -1;
        }
    },
    getCode: function (phone, timeout, regx) {
        var c_conf = this._conf.getCode;
        var getCode_api = c_conf.getCode_api;
        var url_obj = {};
        url_obj[this._conf.token_key] = this.token;
        url_obj[this._conf.item_key] = this.item;
        url_obj[this._conf.phone_key] = phone;
        Object.assign(url_obj, c_conf.ext);
        var url = this._conf.method == "get" ? this._conf.url + getCode_api + "?" + this.encodeFormData(url_obj) : this._conf.url + getCode_api;
        var timeout = timeout ? timeout : 30;
        try {
            var code = -1,
                k = 0;
            while (code == -1 && k < Math.ceil(timeout / 3)) {
                toastLog("未获取到短信,等待3秒重试！");
                sleep(3000);
                var res = this._conf.method === "get" ? this.hddp(url) : this.hddp(url, url_obj);
                var code = this.regxCode(res, regx);  // regxCode() 处理失败返回 -1
                k = k + 1;
            }
            if (code == -1) {
                console.error("获取短信验证码超时！");
                return -1;
            }
            return code;
        } catch (e) {
            console.error("验证码接口请求失败！");
            return -1;
        }
    },
    recPhone: function (phone) {
        var r_conf = this._conf.recPhone;
        var recPhone_api = r_conf.recPhone_api;
        var url_obj = {};
        url_obj[this._conf.token_key] = this.token;
        url_obj[this._conf.item_key] = this.item;
        url_obj[this._conf.phone_key] = phone;
        var url = this._conf.method == "get" ? this._conf.url + recPhone_api + "?" + this.encodeFormData(url_obj) : this._conf.url + recPhone_api;
        try {
            var res = this._conf.method === "get" ? this.hddp(url) : this.hddp(url, url_obj);
            console.log(res);
            return res;
        } catch (e) {
            console.error("释放手机号失败！");
            return -1;
        }
    },
    adbPhone: function (phone) {
        var a_conf = this._conf.adbPhone;
        var adbPhone_api = a_conf.adbPhone_api;
        var url_obj = {};
        url_obj[this._conf.token_key] = this.token;
        url_obj[this._conf.item_key] = this.item;
        url_obj[this._conf.phone_key] = phone;
        var url = this._conf.method == "get" ? this._conf.url + adbPhone_api + "?" + this.encodeFormData(url_obj) : this._conf.url + adbPhone_api;
        try {
            var res = this._conf.method === "get" ? this.hddp(url) : this.hddp(url, url_obj);
            console.log(res);
            return res;
        } catch (e) {
            console.error("拉黑手机号失败！");
            return -1;
        }
    }
}

Tmd.prototype.init = function (pt, user, pwd, item, vno, phoneType) {
    if (arguments.length < 4) {
        console.error("请正确填写初始化参数！");
        return -1;
    }
    this._conf = _config[pt];
    this.user = user;
    this.pwd = pwd;
    this.item = item;
    this.vno = vno;
    this.phoneType = phoneType;
    this.token = this.getToken();
};

Tmd.prototype.regxToken = function (res, rule) {
    if (typeof res == "object") {
        for (var name in res) {
            if (res[name] < 20) {
                continue;
            }
            var token = res[name];
        }
        if (token) {
            return token;
        } else {
            console.error("Token值匹配失败！");
        }
    } else if (typeof res == "string") {
        if (res.indexOf(rule) == -1) {
            console.error("Token返回值中未找到【" + rule + "】分割符！");
            return -1;
        }
        var res = res.split(rule).find(function (e) {
            return e.length > 20;
        });
        if (!res) {
            console.log("Token值匹配失败！");
            return -1;
        };
        return res;
    }
}

Tmd.prototype.regxPhone = function (str) {
    var temp = this.res_format(str)
    if (temp.length < 11) {
        console.error("获取手机号失败！");
        return -1;
    } else {
        return temp.match(/\d{11}/)[0];
    }
}

Tmd.prototype.regxCode = function (str, regx) {
    var temp = this.res_format(str);
    if (!regx) {
        var regx = /\d{4,8}/;
    }
    var res = regx.test(temp);
    if (!res) {
        return -1;
    } else {
        return temp.match(regx)[0];
    }
}

Tmd.prototype.hddp = function (url, data) {
    if (arguments.length < 1) {
        console.error("请填写API请求必要参数！");
        return -1;
    }
    if (this._conf.method === "get") {
        try {
            var res = http.get(url);
            if (res.statusCode != 200) {
                console.error("请求失败: " + res.statusCode + " " + res.statusMessage);
                return -1;
            }
            try {
                var res = this._conf.resType === "string" ? res.body.string() : res.body.json();
            } catch (e) {
                console.error("获取API-GET返回值出错！");
                return -1;
            }
        } catch (err) {
            console.error('API-GET请求失败！');
        }
    } else if (this._conf.method == "post" && data) {
        try {
            var res = http.post(url, data);
            if (res.statusCode != 200) {
                console.error("请求失败: " + res.statusCode + " " + res.statusMessage);
                return -1;
            }
            try {
                var res = this._conf.resType === "string" ? res.body.string() : res.body.json();
            } catch (e) {
                console.error("获取API-POST返回值出错！");
                return -1;
            }
        } catch (err) {
            console.error('API-POST请求失败！');
        }
    } else {
        console.error("API请求参数格式错误！")
    }
    // 是否开启调试
    if (this.debug) {
        console.warn('\n\r' + '[调试]  请求URL:' + url + '\n\r' + '[调试]  返回值:' + res);
    };
    return res;
}

Tmd.prototype.res_format = function (res) {
    return typeof res === "object" ? JSON.stringify(res) : res;
}

Tmd.prototype.encodeFormData = function (data, arr) {
    if (!data) return "";
    var temp = [];
    if (!arr) arr = [];
    for (var name in data) {
        if (arr.indexOf(name) != -1) {
            continue;
        }
        var value = data[name].toString();
        temp.push(name + '=' + value);
    }
    return temp.join('&');
}